layui.use(['layer', 'table', 'element'], function () {
    let layer = layui.layer //弹层
        , table = layui.table //表格


    //第一个实例
    table.render({
        elem: '#checkList'
        , url: '/repository/list' //数据接口
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        , page: { //开启分页
            limit: 10,
            limits: [10, 15, 20]
        }
        , toolbar: '#headerBar'
        , cols: [
            [ //表头
                {type: 'checkbox', fixed: 'left'},
                {type: 'numbers', title: '序号', align: 'center', width: 60, fixed: 'left'},
                {field: 'id', title: 'ID', align: 'center', width: 80}
                , {field: 'title', title: '书名', align: 'center', width: 200}
                , {field: 'author', title: '作者', align: 'center', width: 240}
                , {field: 'press', title: '出版社', align: 'center', width: 300}
                , {field: 'pressTime', title: '出版时间', align: 'center', width: 120}
                , {field: 'description', title: '简介', align: 'center', width: 200}
                , {field: 'src', title: '文件路径', align: 'center', width: 340}
                , {
                field: 'img', title: '图片地址', align: 'center', width: 100, templet: function (d) {
                    if (d.img === undefined || d.img === null || d.img === "") {
                        return "暂无资源";
                    }
                }
            }
                , {
                field: 'size', title: '资源大小', align: 'center', width: 140, templet: function (d) {
                    let size = d.size / 1024;
                    return size.toFixed(3) + "MB";
                }
            }
                , {
                field: 'uploadTime', title: '上传时间', align: 'center', width: 200,
                templet: "<div>{{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"
            }
                , {
                field: 'isFree', title: '是否免费', align: 'center', width: 100, templet: function (d) {
                    if (d.isFree === 1) {
                        return "免费";
                    } else {
                        return "收费";
                    }

                }
            }
                , {field: 'iSBN', title: '国际标准书号', align: 'center', width: 200}
                , {align: 'center', title: '操作', toolbar: '#checkListBar', fixed: 'right', unresize: true, width: 220}
            ]
        ]
        , parseData: function (res) {
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        }
    });


    // 工具头
    table.on('toolbar(checkTable)', function (obj) {
        switch (obj.event) {
            case 'refresh': // 单击了刷新按钮
                // 表格重载
                tableObj.reload();
                break;
            case 'checkBatch':
                toCheckBatch();
                break;
            case 'deleteBatch':
                toDeleteBatch();
                break;
        }
    });


    // 表格重置
    let tableObj = table.reload('checkList', {
        url: '/repository/list', //数据接口
        request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        , page: { //开启分页
            curr: 1,
            limit: 10,
            limits: [10, 15, 20]
        }
    })


    // 批量审核
    function toCheckBatch() {
        let checkStatus = table.checkStatus('checkList'),
            data = checkStatus.data,
            idList = [],
            itemList = [];
        data.forEach(function (n, i) {
            idList.push(n.id);
            let item = {}
            item.id = n.id;
            item.title = n.title;
            item.author = n.author;
            item.press = n.press;
            item.pressTime = n.pressTime;
            item.description = n.description;
            item.src = n.src;
            item.img = n.img;
            item.size = n.size;
            item.isFree = n.isFree;
            item.uploadTime = n.uploadTime;
            item.iSBN = n.iSBN;
            itemList.push(item);
        });
        $.ajax({
            url: '/depot/checkBatch',
            type: 'post',
            data: JSON.stringify({idList: idList, itemList: itemList}),
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            success: function (res) {
                console.log("批量上架的回调数据:" + res);
                if (res.row !== 0) {
                    layer.open({
                        title: '提示',
                        icon: 1,
                        content: '一共添加了<span style="color: red">' + res.row + '</span>条记录到书架中，还需要完善!',
                        shadeClose: true,
                        time: 1800
                    });
                    // 表格重载
                    setTimeout(function () {
                        tableObj.reload();
                    }, 1400);
                } else {
                    layer.open({
                        title: '提示',
                        icon: 0,
                        content: '审核失败！请稍后再试！',
                        shadeClose: true,
                        time: 2000
                    });
                }
            },
            error: function () {
                layer.msg("网络异常……", {icon: 2, anim: 6});
            }

        })

    }

    // 批量删除
    function toDeleteBatch() {
        let checkStatus = table.checkStatus('checkList'),
            data = checkStatus.data,
            list = [];
        data.forEach(function (n, i) {
            list.push(n.id);
        });
        $.ajax({
            url: '/depot/deleteBatch',
            type: 'post',
            data: JSON.stringify({idList: list}),
            contentType: 'application/json;charset=utf-8',
            success: function (row) {
                if (row !== 0) {
                    layer.open({
                        title: '提示',
                        icon: 1,
                        content: '一共删除<span style="color: red">' + row + '</span>条记录!',
                        shadeClose: true,
                        time: 1800
                    });
                    // 删除数据表格记录
                    setTimeout(function () {
                        tableObj.reload();
                    }, 1400);
                } else {
                    layer.open({
                        title: '提示',
                        icon: 0,
                        content: '审核失败！请稍后再试！',
                        shadeClose: true,
                        time: 2000
                    });
                }
            },
            error: function () {
                layer.msg("网络异常……", {icon: 2, anim: 6});
            }
        })
    }

    // 监听复选框
    // table.on('checkbox(checkTable)', function (obj) {
    //     let checkStatus = table.checkStatus('checkList'),
    //         data = checkStatus.data,
    //         delList = [];
    //     data.forEach(function (n, i) {
    //         delList.push(n.id);
    //     });
    //     for (i = 0; i < delList.length; i++) {
    //         console.log("要删除的ID是：" + delList[i]);
    //     }
    // });


    // 工具条（监听行）
    table.on('tool(checkTable)', function (obj) {
        let data = obj.data;    // 获取当前行数据
        let layEvent = obj.event;   // 获取lay-event对应的值（show、agree、delete）
        switch (obj.event) {
            case 'preview':   // 预览
                toPreview(data);
                break;
            case 'ratify':  // 审核
                toCheck(data, obj);
                break;
            case 'delete':  // 删除
                deleteOne(data, obj);
                break;
        }
    });


    // 请求审核图书
    function toCheck(data, obj) {
        $.ajax({
            url: '/depot/check',
            type: 'post',
            data: JSON.stringify({id: data.id}),
            contentType: 'application/json;charset=utf-8',
            success: function (row) {
                if (row !== 0) {
                    layer.open({
                        title: '提示',
                        icon: 1,
                        content: '图书：<span style="color: #f38181">' + data.title + '</span>已通过审核！',
                        shadeClose: true,
                        time: 1800
                    });
                    // 删除数据表格记录
                    setTimeout(function () {
                        obj.del();
                    }, 1400);
                } else {
                    layer.open({
                        title: '提示',
                        icon: 0,
                        content: '审核失败！请稍后再试！',
                        shadeClose: true,
                        time: 2000
                    });
                }
            },
            error: function () {
                layer.msg("网络异常……", {icon: 2, anim: 6});
            }
        })
    }


    // 删除书库中的图书
    function deleteOne(data, obj) {
        layer.confirm('确定删除<span style="color: red">《' + data.title + '》</span>嘛？', {icon: 3, title: '警告'},
            function () {
                $.ajax({
                    url: '/depot/delete',
                    type: 'post',
                    data: JSON.stringify({id: data.id}),
                    contentType: 'application/json;charset=UTF-8',
                    success: function (data) {
                        if (data) {
                            layer.msg('删除成功！', {icon: 1, time: 1300}, function () {
                                obj.del();
                            });
                        } else {
                            layer.msg('删除失败！', {icon: 0, time: 1600}, function () {
                            });
                        }
                    },
                    error: function () {
                        layer.msg("网络异常……", {icon: 2, anim: 6});
                    }
                })
            });
    }


    // 管理员预览PDF
    function toPreview(data) {
        let url = "/admin/preview?id=" + data.id;
        window.open(url);
    }


});



